<template>
	<div class="container">
		<el-page-header @back="goback" content="新增投入品">
		</el-page-header>
		<el-form
			style="margin-top:20px;"
		    :model="ruleForm"
		    ref="ruleForm"
		    :rules="rules"
		    :label-position="labelPosition"
		    label-width="120px"
		    class="demo-ruleForm">
		    <el-row>
		        <el-col :span="12">
		            <el-form-item label="类别：" prop="type">
		                <template>
		                    <el-select
		                        v-model="ruleForm.type"
		                        style="width:300px"
		                        placeholder="请选择">
		                        <el-option
		                            v-for="item in typeList"
		                            :key="item.value"
		                            :label="item.label"
		                            :value="item.value"
		                        ></el-option>
		                    </el-select>
		                </template>
		            </el-form-item>
					<el-form-item label="采购批号：" prop="batch">
					    <el-input placeholder="请输入" v-model="ruleForm.batch" style="width: 300px">
					        <template slot="append">
								<el-button @click="addBatch">自动生成</el-button>
					        </template>
					    </el-input>
					</el-form-item>
		           <el-form-item label="生产日期：">
		               <el-date-picker
		                   v-model="ruleForm.producedTime"
		                   type="date"
						   @change="gettime"
		                   value-format="yyyy-MM-dd"
		                   placeholder="请选择"
		                   style="width:300px"
		               ></el-date-picker>
		           </el-form-item>
				   <el-form-item label="采购时间：" prop="buyTime">
				       <el-date-picker
				           v-model="ruleForm.buyTime"
				           type="date"
						   @change="gettime"
				           value-format="yyyy-MM-dd"
				           placeholder
				           style="width:300px"
				       ></el-date-picker>
					 </el-form-item>
		            <el-form-item label="投入品照片：">
		                <el-upload
		                    class="upload-poster"
		                    action="https://jsonplaceholder.typicode.com/posts/"
		                    :show-file-list="false"
		                    :on-change="imgPreview"
		                    :auto-upload="false"
		                >
		                    <img v-if="inputsImg" :src="inputsImg" class="avatar" />
		                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
		                </el-upload>jpg、png、gif格式，60x60像素，不超过2MB
		            </el-form-item>
		           
		        </el-col>
		        <el-col :span="10">
					<el-form-item label="品名：" prop="inputsName">
					    <el-input
					        placeholder="请输入内容"
					        v-model="ruleForm.inputsName"
					        style="width:300px"
					    ></el-input>
					</el-form-item>
		           <el-form-item label="数量：" prop="number">
		               <el-input placeholder="请输入" v-model="ruleForm.number" style="width: 300px">
		                   <template slot="append">
		                       <el-select
		                           v-model="ruleForm.units"
		                           placeholder="单位"
		                           style="width:80px !important">
		                           <el-option
		                               v-for="item in unitsList"
		                               :key="item.id"
		                               :label="item.name"
		                               :value="item.name"
		                           ></el-option>
		                       </el-select>
		                   </template>
		               </el-input>
		           </el-form-item>
                   <el-form-item label="规格：" prop="spec">
                       <el-input placeholder="请输入" v-model="ruleForm.spec" style="width: 300px">
                           <template slot="append">
                               <el-select
                                   v-model="ruleForm.specUnits"
                                   placeholder="单位"
                                   style="width:80px !important">
                                   <el-option
                                       v-for="item in unitsList"
                                       :key="item.id"
                                       :label="item.name"
                                       :value="item.name"
                                   ></el-option>
                               </el-select>
                           </template>
                       </el-input>
                   </el-form-item>
		            <el-form-item label="保质期：">
		                <el-input v-model="ruleForm.expirationDate" style="width: 300px">
							<template slot="append">
								月
							</template>
						</el-input>
		            </el-form-item>
		           <el-form-item label="供应商名称：" prop="supplyName">
		               <template>
		                   <el-select
		                       v-model="supplyName"
		                       @change="changeSupply"
		                       style="width:300px"
							   value-key="id"
		                       placeholder="请选择"
		                   >
		                       <el-option
		                           v-for="item in supplyList"
		                           :key="item.id"
		                           :label="item.supplierName"
		                           :value="item"
		                       ></el-option>
		                   </el-select>
		               </template>
		           </el-form-item>
		            
		           
		        </el-col>
		    </el-row>
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="goback">取消</el-button>
		    </el-form-item>
		</el-form>
	</div>
</template>

<script>
import { inputs_save } from '@/request/breedApi';
import { unit_findByList,supplier_findByAll } from '@/request/api';
	export default{
		data(){
			return{
				supplyName:'',
				batch:'',
				labelPosition: 'right',
				supplyList:[],
				unitsList:[],
				name:'',
				inputsImg:'',
				typeList: [
				    {
				        value: '饲料添加剂',
				        label: '饲料添加剂'
				    },
				    {
				        value: '饲料',
				        label: '饲料'
				    },
					{
					    value: '药品',
					    label: '药品'
					},
				    {
				        value: '其他',
				        label: '其他'
				    }
				],
				ruleForm:{
				   batch:''
				},
				rules:{
					type: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					batch: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					buyTime: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					inputsName: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					number: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					
				}
			}
		},
		created() {
			
		},
		mounted() {
			this.init();
		},
		methods:{
			gettime(){
				// var oDate1 = new Date(this.ruleForm.producedTime)
				// var oDate2 = new Date(this.ruleForm.buyTime)
				if(this.ruleForm.producedTime != "" && this.ruleForm.buyTime != ""){
					var oDate1 = new Date(this.ruleForm.producedTime)
					var oDate2 = new Date(this.ruleForm.buyTime)
					// console.log(oDate1)
					// console.log(oDate2)
					if(oDate1 > oDate2){
						this.$notify({
						    title: '提示',
						    message: '采购时间不得早于生产时间',
						    type: 'info'
						});
						this.ruleForm.producedTime =""
						this.ruleForm.buyTime = ""
					}
				}
			},
			addBatch() {
				// console.log(111)
				var d = new Date();
				var curr_date = d.getDate();
				var curr_month = d.getMonth() + 1; 
				var curr_year = d.getFullYear();
				String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
				String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
				var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
				this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
				this.batch = this.ruleForm.batch
				// console.log(this.ruleForm.batch)
			},
		        init() {
                     unit_findByList("").then((res) => {
                          if (res.code == 200) {
                            this.unitsList = res.data;
                          }
                     });
					  supplier_findByAll("").then((res) => {
						   if (res.code == 200) {
							 this.supplyList = res.data;
						   }
					  });
                },

			// 选择图片
			imgPreview(file,fileList){
			      this.inputsImg =  URL.createObjectURL(file.raw);
			     let fileName = file.name;
			    let regex = /(.jpg|.gif|.png)$/;
			     if (regex.test(fileName.toLowerCase())) {
			         this.ruleForm.files = file.raw
			        this.ruleForm.inputsImg = file.name
			    } else {
			         this.$message.error('请选择图片文件');
			     }
			},

			// 供应商
			changeSupply(ele){
                this.ruleForm.supplyId=ele.id;
                this.ruleForm.supplyName=ele.supplierName;
			},
			// 返回上一页 顶部使用 和取消按钮
			goback(){
				this.$router.go(-1)
			},
            // addBatch() {
            //     var d = new Date();
            //     var curr_date = d.getDate();
            //     var curr_month = d.getMonth() + 1;
            //     var curr_year = d.getFullYear();
            //     String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
            //     String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
            //     var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
            //     this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
            // },

			// 提交
			submitrule(formName){
				this.$refs[formName].validate((valid) => {
				    if (valid) {
						console.log(this.ruleForm.number)
						console.log(this.ruleForm.units)
						if(this.ruleForm.number != ""){
							if(this.ruleForm.units == "" || this.ruleForm.units == undefined){
								this.$notify({
									title: '提示',
									message: '数量单位不能为空',
									type: 'info'
								});
								return false
							}
						}
						if(this.ruleForm.spec != ""){
							if(this.ruleForm.specUnits == "" || this.ruleForm.specUnits == undefined){
								this.$notify({
									title: '提示',
									message: '规格单位不能为空',
									type: 'info'
								});
								return false
							}
						}
				        this.$confirm('请仔细核对所填信息，提交后不能修改！', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
			
							let formdata = new FormData()
							for (var a in this.ruleForm) {
								if (this.ruleForm[a] == null || this.ruleForm[a] == 'null') {
									this.ruleForm[a] = '';
									formdata.append(a, '');
								} else {
									formdata.append(a, this.ruleForm[a]);
								}
							}
						   inputs_save(formdata).then((res) => {
								if (res.code == 200) {
									this.$router.go(-1)
								}
							 });
						})
				    } else {
				        return false;
				    }
				})
				
			}
		}
	}
</script>

<style scoped>
	.avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    width:180px;
	    overflow: hidden;
	  }
	  .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .el-upload--text{
	      width:180px;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 178px;
	    height: 178px;
	    line-height: 178px;
	    text-align: center;
	  }
	  .avatar {
	    width: 178px;
	    height: 178px;
	    display: block;
	  }
</style>
